package com.hang.esService.impl;

import com.hang.esEntity.SubjectInfoEs;
import com.hang.esService.SubjectEsService;
import com.hang.repository.SubjectEsRepository;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class SubjectEsServiceImpl implements SubjectEsService {

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Resource
    private SubjectEsRepository subjectEsRepository;

    @Override
    public void createIndex() {
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(SubjectInfoEs.class);
        indexOps.create();
        Document document = indexOps.createMapping(SubjectInfoEs.class);
        indexOps.putMapping(document);
    }

    @Override
    public void getDocs() {
        List<SubjectInfoEs> list = new ArrayList<>();
        list.add(new SubjectInfoEs(1L,"redis是什么？","是一个高可用的缓存","hang",new Date()));
        list.add(new SubjectInfoEs(2L,"mysql是什么？","是一个数据库","hang",new Date()));
        subjectEsRepository.saveAll(list);
    }

    @Override
    public void find() {
        Iterable<SubjectInfoEs> all = subjectEsRepository.findAll();
        for (SubjectInfoEs subjectInfoEs : all) {
            log.info(subjectInfoEs.getSubjectName());
            log.info(subjectInfoEs.getSubjectAnswer());
        }
    }

    @Override
    public void search() {
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("subjectName", "redis")).build();
        SearchHits<SubjectInfoEs> search = elasticsearchRestTemplate.search(searchQuery, SubjectInfoEs.class);
        List<SearchHit<SubjectInfoEs>> hits = search.getSearchHits();
        log.info(hits.toString());
    }
}
